package academic.emailClient.view;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;

import academic.emailClient.model.entities.Filter;

public class ManageFIlterView extends JPanel {

	private JTabbedPane tabbedPane;
	private JPanel tab1Panel=new JPanel(new FlowLayout(FlowLayout.CENTER, 3,3));
	    
    private JLabel from=new JLabel("From                      ");
	private JLabel to=new JLabel("To                           ");
	private JLabel subject=new JLabel("Subject                  ");
	private JLabel includeTheWord=new JLabel("Include the world");
	private JLabel date=new JLabel("Date                       ");
	private JLabel empty=new JLabel("                             ");
	private JLabel filterName=new JLabel("Filter Name          ");
	private JLabel filterPathLabel=new JLabel("Save filter to    ");
	final static String[] DAYS ={"--", "01","02","03","04","05","06","07","08","09","10","11","12","13", "14","15","16","17", "18","19","20","21", 
			"22","23","24","25", "26", "27", "28", "29", "30", "31"};	
	final static String[] MONTHS ={"--", "January","February","March","April","May","June","July","August","Spetember",
			"October","November","December"};	
	 final static String  YEAR[] = {"--", "2013","2014","2015","2016", "2017","2018","2019","2020","2021","2022","2022","2023"};
	 private IndexingTheMails indexMail=new IndexingTheMails();
	 private static JTextField fromTxt=new JTextField(25);
	 private static JTextField toTxt=new JTextField(25);
	 private static JTextField subjectTxt=new JTextField(25);
	 private static JTextField includeTheWordTxt=new JTextField(25);
	 private JTextField filterNameTxt=new JTextField(25);	
	 private static JComboBox daysCb= new JComboBox(DAYS);
	 private static JComboBox monthsCb= new JComboBox(MONTHS);
	 private static JComboBox yearCb= new JComboBox(YEAR);
	 private static JComboBox modifyFiltercb;	
	 Icon iconAdd = createImageIcon("icons/add.png");
	 private JComboBox filterPathCombo = new JComboBox(); 
	 private HashMap<String, String> paths;
	 private JLabel emptyLabel=new JLabel("                  ");
	 private JButton modifyButton = new JButton(" Modify ");	       
	 private JButton cancelButton = new JButton(" Cancel ");
	 private JButton deleteButton = new JButton(" Delete ");
	 private JPanel panel2_buttons;
	
	 /**
	  * Constructor
	  */
	public ManageFIlterView() {   	
       super(new GridLayout(1, 1));    
       tabbedPane = new JTabbedPane();    
       //Load combo box with available template files
       modifyFiltercb = new JComboBox();
       modifyButton.setMnemonic(KeyEvent.VK_M);
       cancelButton.setMnemonic(KeyEvent.VK_C);
       deleteButton.setMnemonic(KeyEvent.VK_D);
       panel2_buttons = new JPanel(new FlowLayout(FlowLayout.CENTER, 3,3));
       panel2_buttons.setSize(400, 50);
       panel2_buttons.add(emptyLabel);
       panel2_buttons.add(modifyButton);
       panel2_buttons.add(cancelButton);
       panel2_buttons.add(deleteButton);
       tab1Panel.setPreferredSize(new Dimension(400, 300));
       tab1Panel.setLayout(new FlowLayout(FlowLayout.LEFT, 3,3));
	}
	
   /** Returns an ImageIcon, or null if the path was invalid. */
   protected static ImageIcon createImageIcon(String path1) {
       java.net.URL imgURL = CreateNewTemplateView.class.getResource(path1);
       if (imgURL != null) {
           return new ImageIcon(imgURL);
       } else {
           System.err.println("Couldn't find file: " + path1);
           return null;
       }
   }
    
	/**
	 * returns file names of all the files in email folders
	 * @return
	 */
	private ArrayList<String> getAllFilesNamesInTemplatesFolder(){
		ArrayList<String> names = new ArrayList<String>();
		names.add( "Select Template");
		int i = 1;
		File folder = new File("Templates");
		for (File  f: folder.listFiles()){
			if(f.getName() != null) {
				names.add(f.getName());
			 i++;
			}
		}
		return names;
	}

   /**
    * Create the TabbedPane
    */
   public JTabbedPane getTabbedPane(HashMap<String, String> paths, ArrayList<Filter> filters) {
	   tabbedPane.removeAll();         
       loadFilterPathsComboBox(paths, filters);       
       loadFiltersComboBox(paths, filters);
       
       tab1Panel.add(filterName);
       tab1Panel.add(modifyFiltercb);
       tab1Panel.add(from);
       tab1Panel.add(fromTxt);
       tab1Panel.add(to);
       tab1Panel.add(toTxt);
       tab1Panel.add(subject);
       tab1Panel.add(subjectTxt);	
       tab1Panel.add(includeTheWord);
       tab1Panel.add(includeTheWordTxt);		
       tab1Panel.add(date);
       tab1Panel.add(daysCb);
       tab1Panel.add(monthsCb);
       tab1Panel.add(yearCb);
	   tab1Panel.add(empty);
	   tab1Panel.add(filterPathLabel);
	   tab1Panel.add(filterPathCombo);
	   tab1Panel.add(panel2_buttons);	   
       tabbedPane.addTab("Manager Filters", iconAdd, tab1Panel, "Manager Filters Tab");
       tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
       add(tabbedPane);
      
       //Use scrolling tabs.
       tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
       return tabbedPane;
   }
   
   /**
    * load Filter Paths Combo Box
    * @param paths2
    * @param filters
    */
	public void loadFilterPathsComboBox(HashMap<String, String> paths2, ArrayList<Filter> filters) {
		 String[] filterPathstring=createMenuItem(paths2);  
		 //flush filterPathCombo
	       filterPathCombo.removeAllItems();
	       filterPathCombo.revalidate();		
		   filterPathCombo.repaint();
	       //Load
	       for (String item : filterPathstring){
	    	   filterPathCombo.addItem(item);    	   
	       }
	       //update tab	
			filterPathCombo.setMaximumSize( filterPathCombo.getPreferredSize());		
			filterPathCombo.revalidate();		
			filterPathCombo.repaint();
	}
	
	/**
	 * load Filters ComboBox
	 * @param paths2
	 * @param filters
	 */
	public void loadFiltersComboBox(HashMap<String, String> paths2, ArrayList<Filter> filters) {
		 String[] filterPathstring=createMenuItem(paths2);  
		  //flush modifyFiltercb
	       modifyFiltercb.removeAllItems();
	       modifyFiltercb.revalidate();		
	       modifyFiltercb.repaint();
	      //Load
	       for (Filter item : filters){
	    	   modifyFiltercb.addItem(item.getName());    	   
	       }
	       
	       modifyFiltercb.setPreferredSize(new Dimension(280, 25));	
	       modifyFiltercb.revalidate();		
	       modifyFiltercb.repaint();
	}

	/**
	 * get Modify Button
	 * @return
	 */
	public JButton getModifyButton(){
		return modifyButton;
	}
	
	/**
	 * get Cancel Button
	 * @return
	 */
	public JButton getCancelButton(){
		return cancelButton;
	}
	
	/**
	 * get Delete Button
	 * @return
	 */
	public JButton getDeleteButton(){
		return deleteButton;
	}
	
	/**
	 * create Menu Item
	 * @param paths
	 * @return
	 */
	private String[] createMenuItem(HashMap<String, String> paths){
   	this.paths=paths;
   	Set<String> visiblePathsSet = paths.keySet();
		Iterator<String> iterator = visiblePathsSet.iterator();
		 String[] filterPaths=new String[visiblePathsSet.size()];
		for (int i=0;i< visiblePathsSet.size();i++)
			filterPaths[i]=iterator.next();
		return filterPaths;		
	}
	
   /**
    * add Panel To Tab1
    * @param panel
    */
	public void addPanelToTab1(JPanel panel){
	   tab1Panel.add(panel);	    
   }
   
	/**
	 * get Modify Filter Cb
	 * @return
	 */
    public JComboBox getModifyFilterCb(){
   	return modifyFiltercb;
   }

    /**
     * update filter Fields
     * @param string
     * @param paths
     * @param filters
     */
	public void updateFields(String string, HashMap<String, String> paths, ArrayList<Filter> filters) {
		Filter filter = getcbSelectedFilter( filters);
		fromTxt.setText(filter.getQuery().get(0).toString());
		toTxt.setText(filter.getQuery().get(1).toString());
		subjectTxt.setText(filter.getQuery().get(2).toString());
		includeTheWordTxt.setText(filter.getQuery().get(3).toString());
		String date = filter.getQuery().get(4).toString();
		String destinationPath = filter.getDestinationFolderPath();
		if(!date.isEmpty()){
		String day = date.substring(0, 2);
		String month = date.substring(3, 5);
		String year = date.substring(6, 10);
		daysCb.setSelectedIndex(Integer.parseInt(day));
		monthsCb.setSelectedIndex(Integer.parseInt(month));
		for(int i = 0; i< YEAR.length; i++){
			if(YEAR[i].equals(year)){
				yearCb.setSelectedIndex(i);
				}
			}
		  }
		int pathIndex =getPathIndex(destinationPath);
		filterPathCombo.setSelectedIndex(pathIndex);
		//update tab
		daysCb.setMaximumSize( daysCb.getPreferredSize() );
		monthsCb.setMaximumSize( monthsCb.getPreferredSize() );
		yearCb.setMaximumSize( yearCb.getPreferredSize() );
		filterPathCombo.setMaximumSize( yearCb.getPreferredSize() );
		daysCb.revalidate();
		filterPathCombo.revalidate();
		monthsCb.revalidate();  
		yearCb.revalidate();  
		daysCb.repaint();
		filterPathCombo.repaint();
		monthsCb.repaint();  
		yearCb.repaint();  
		}
	
	/**
	 * get Modify Filter Cb Fields
	 * @return
	 */
	private ArrayList<String> getModifyFilterCbFields(){
		ArrayList<String> items = new ArrayList <String>();
		for (int i = 0; i< modifyFiltercb.getItemCount(); i++ ){
			items.add(modifyFiltercb.getItemAt(i).toString());
		}
		return items;
	}
	
	/**
	 * get cb Selected Filter
	 * @param filters
	 * @return
	 */
	public Filter getcbSelectedFilter(ArrayList<Filter> filters){
		for(Filter filter: filters){
			if(filter.getName().equals(modifyFiltercb.getSelectedItem().toString())){
				return filter;
			}
		}
		return null;
	}
	
	/**
	 * get Path Index
	 * @param destinationPath
	 * @return
	 */
	private int getPathIndex(String destinationPath){
		for (int i = 0; i<  filterPathCombo.getItemCount(); i++){
			String pathFromCombo = paths.get(filterPathCombo.getSelectedItem().toString());
			if(pathFromCombo.equals(destinationPath))
			{
				return i;
			 }
		 }
		return 0;
	}	
	
	/**
	 * set Path
	 * @param paths
	 */
	public void setPath(HashMap<String, String> paths){
		this.paths = paths;
	}

	public Filter updatedFilter(Filter filter_) {
		// TODO Auto-generated method stub
		Filter filter = filter_;
		String ff= filterPathCombo.getSelectedItem().toString();
		filter.setDestinationFolderPath(filterPathCombo.getSelectedItem().toString());
		//build query
		ArrayList<String> query = new ArrayList<String> ();
		query.add(fromTxt.getText().toString());
		query.add(toTxt.getText().toString());
		query.add(subjectTxt.getText().toString());
		query.add(includeTheWordTxt.getText().toString());
		String day = daysCb.getSelectedItem().toString();
		String month = "";
		if(monthsCb.getSelectedIndex() < 10){
			month = "0" + Integer.toString(monthsCb.getSelectedIndex());
		}
		else{
			month = Integer.toString(monthsCb.getSelectedIndex());
		}		
		String year = yearCb.getSelectedItem().toString();
		String date = day + "/"+ month + "/" + year;
		query.add(date);		
		filter.setQuery(query);		
		return filter;
	}
}

